<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="素材名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入素材名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="素材类型" prop="materialType">
        <el-select v-model="queryParams.materialType" placeholder="请选择素材类型" clearable>
          <el-option
            v-for="dict in dict.type.advertisement_material_type"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['advertisement:material:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['advertisement:material:edit']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['advertisement:material:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['advertisement:material:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="素材ID" align="center" prop="materialId" width="80" />
      <el-table-column label="素材名称" align="center" prop="materialName" :show-overflow-tooltip="true" />
      <el-table-column label="素材类型" align="center" prop="materialType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.advertisement_material_type" :value="scope.row.materialType" />
        </template>
      </el-table-column>
      <el-table-column label="素材预览" align="center" width="120">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.materialType === 1"
            :src="scope.row.fileUrl"
            :preview-src-list="[scope.row.fileUrl]"
            style="width: 80px; height: 45px"
            fit="cover"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline" />
            </div>
          </el-image>
          <el-button
            v-else-if="scope.row.materialType === 2"
            type="text"
            icon="el-icon-video-play"
            @click="handlePreview(scope.row)"
          >预览</el-button>
          <el-button
            v-else-if="scope.row.materialType === 3"
            type="text"
            icon="el-icon-headset"
            @click="handlePreview(scope.row)"
          >播放</el-button>
          <el-button
            v-else-if="scope.row.materialType === 4"
            type="text"
            icon="el-icon-document"
            @click="handlePreview(scope.row)"
          >查看</el-button>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="文件大小" align="center" prop="fileSize" width="100">
        <template slot-scope="scope">
          {{ formatFileSize(scope.row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column label="播放时长" align="center" prop="duration" width="100">
        <template slot-scope="scope">
          {{ scope.row.duration }}秒
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['advertisement:material:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['advertisement:material:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handlePreview(scope.row)"
          >预览</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改素材对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="素材名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入素材名称" />
        </el-form-item>
        <el-form-item label="素材类型" prop="materialType">
          <el-select v-model="form.materialType" placeholder="请选择素材类型">
            <el-option
              v-for="dict in dict.type.advertisement_material_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="素材文件" prop="fileUrl">
          <file-upload v-model="form.fileUrl" :file-type="getFileType(form.materialType)" />
        </el-form-item>
        <el-form-item label="播放时长" prop="duration">
          <el-input-number v-model="form.duration" :min="1" :max="300" />
          <span style="margin-left: 10px;">秒</span>
        </el-form-item>
        <el-form-item label="素材描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入素材描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 素材预览对话框 -->
    <el-dialog title="素材预览" :visible.sync="previewOpen" width="800px" append-to-body>
      <div class="preview-container">
        <el-image
          v-if="previewData.materialType === 1"
          :src="previewData.fileUrl"
          style="max-width: 100%; max-height: 500px;"
          fit="contain"
        />
        <video
          v-else-if="previewData.materialType === 2"
          :src="previewData.fileUrl"
          controls
          style="max-width: 100%; max-height: 500px;"
        />
        <audio
          v-else-if="previewData.materialType === 3"
          :src="previewData.fileUrl"
          controls
          style="width: 100%;"
        />
        <div
          v-else-if="previewData.materialType === 4"
          style="max-width: 100%; max-height: 500px; overflow-y: auto; padding: 20px; border: 1px solid #ddd;"
          v-html="previewData.content || '暂无文本内容'"
        />
        <div v-else>
          <p>无法预览该类型的素材</p>
        </div>
      </div>
      <div style="margin-top: 20px;">
        <p><strong>素材名称：</strong>{{ previewData.materialName }}</p>
        <p><strong>素材类型：</strong>{{ getMaterialTypeName(previewData.materialType) }}</p>
        <p><strong>播放时长：</strong>{{ previewData.duration }}秒</p>
        <p><strong>文件大小：</strong>{{ formatFileSize(previewData.fileSize) }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial, toggleMaterialStatus } from '@/api/advertisement/material'

export default {
  name: 'Material',
  dicts: ['advertisement_material_type', 'sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 素材表格数据
      materialList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示预览弹出层
      previewOpen: false,
      // 预览数据
      previewData: {},
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialName: null,
        materialType: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        materialName: [
          { required: true, message: '素材名称不能为空', trigger: 'blur' }
        ],
        materialType: [
          { required: true, message: '素材类型不能为空', trigger: 'change' }
        ],
        fileUrl: [
          { required: true, message: '请上传素材文件', trigger: 'blur' }
        ],
        duration: [
          { required: true, message: '播放时长不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询素材列表 */
    getList() {
      this.loading = true
      listMaterial(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.materialList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        materialId: null,
        materialName: null,
        materialType: null,
        fileUrl: null,
        duration: 5,
        description: null,
        status: 0
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.materialId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加广告素材'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const materialId = row.materialId || this.ids
      getMaterial(materialId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改广告素材'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.materialId != null) {
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addMaterial(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const materialIds = row.materialId || this.ids
      this.$modal.confirm('是否确认删除广告素材编号为"' + materialIds + '"的数据项？').then(function() {
        return delMaterial(materialIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 状态修改 */
    handleStatusChange(row) {
      const text = row.status === 1 ? '启用' : '停用'
      this.$modal.confirm('确认要"' + text + '""' + row.materialName + '"素材吗？').then(function() {
        return toggleMaterialStatus(row.materialId, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
      }).catch(function() {
        row.status = row.status === 1 ? 0 : 1
      })
    },
    /** 预览素材 */
    handlePreview(row) {
      this.previewData = row
      this.previewOpen = true
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('advertisement/material/export', {
        ...this.queryParams
      }, `material_${new Date().getTime()}.xlsx`)
    },
    /** 格式化文件大小 */
    formatFileSize(size) {
      if (!size) return '-'
      const units = ['B', 'KB', 'MB', 'GB']
      let index = 0
      while (size >= 1024 && index < units.length - 1) {
        size /= 1024
        index++
      }
      return size.toFixed(2) + ' ' + units[index]
    },
    /** 根据素材类型获取文件类型 */
    getFileType(materialType) {
      switch (materialType) {
        case 1: // IMAGE
          return ['png', 'jpg', 'jpeg', 'gif']
        case 2: // VIDEO
          return ['mp4', 'avi', 'mov']
        case 3: // AUDIO
          return ['mp3', 'wav']
        case 4: // TEXT
          return []
        default:
          return []
      }
    },
    /** 根据素材类型获取名称 */
    getMaterialTypeName(materialType) {
      const materialTypeDict = this.dict.type.advertisement_material_type
      const found = materialTypeDict.find(item => parseInt(item.value) === materialType)
      return found ? found.label : '未知类型'
    }
  }
}
</script>

<style scoped>
.preview-container {
  text-align: center;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}
</style>
